<template>
  <!-- 计量设备配置计划[填报/编辑/更新/查看] -->
  <base-breadcrumb>
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
                  id="base-breadcrumb" style="position: relative"
                  :rules="queryParams.editModel != 0 ? rules : {}">
      <a-spin :spinning="spinning">
        <a-card>
          <title-name title="基础信息" />
          <custom-form ref="form" :is-validate="true" :rules="rules" :editModel="''" :form="form"
                       :form-list="formList">
            <template slot="fillInTime">
              <a-date-picker v-model="form.fillInTime" value-format="YYYY-MM-DD" placeholder="请选择"
                             :disabled="true" />
            </template>
          </custom-form>
        </a-card>
        <a-card>
          <title-name title="计量设备配置计划" />
          <b-table ref="table" bordered rowKey="key" :isShowTotal="false" :isShowCountBar="false"
                   :showPage="false" :columns="columns" :dataSource="form.planList"
                   :scroll="{ x: 1600}">
            <a-button slot="prefix" type="primary" icon="plus" @click="handleAdd"
                      v-if="queryParams.editModel != 0">新增行</a-button>
            <template slot="mdId" slot-scope="text, record">
              <div v-if="record.isEdit">
                <a-select v-model="record.mdId" placeholder="请选择" style="width: 100%;"
                          @select="handleSelect(record)">
                  <a-select-option v-for="item in deviceNameData" :key="item.id"
                                   :title="item.mdName">
                    {{ item.mdName }}
                  </a-select-option>
                </a-select>
              </div>
              <div v-else>
                <a-tooltip>
                  <template #title>{{ record.mdName }}</template>
                  {{ record.mdName }}
                </a-tooltip>
              </div>
            </template>
            <template slot="mdModelId" slot-scope="text, record">
              <div v-if="record.isEdit">
                <a-select v-model="record.mdModelId" placeholder="请选择" allowClear
                          style="width: 100%;">
                  <a-select-option v-for="item in getMdModelData(record.mdId)" :key="item.id"
                                   :title="item.specificationModel">
                    {{ item.specificationModel }}
                  </a-select-option>
                </a-select>
              </div>
              <div v-else>
                <a-tooltip>
                  <template #title>{{ record.specificationModel }}</template>
                  {{ record.specificationModel }}
                </a-tooltip>
              </div>
            </template>
            <template slot="planMdTotal" slot-scope="text, record,index">
              <div v-if="record.isEdit">
                <BaseInputNumber :min="1" :precision="0" placeholder="请输入"
                                 v-model="record.planMdTotal"
                                 @blur="planMdTotaBlur(record.planMdTotal,index)" />
              </div>
              <div v-else>
                {{ record.planMdTotal }}
              </div>
            </template>
            <template slot="ownMdNum" slot-scope="text, record,index">
              <div v-if="record.isEdit">
                <BaseInputNumber :min="1" :precision="0" placeholder="请输入" v-model="record.ownMdNum"
                                 @blur="ownMdNumBlur(record.ownMdNum,index)" />
              </div>
              <div v-else>
                {{ record.ownMdNum }}
              </div>
            </template>
            <template slot="thirdMdNum" slot-scope="text, record">
              <div v-if="record.isEdit">
                <BaseInputNumber placeholder="请输入" v-model="record.thirdMdNum" :disabled="true" />
              </div>
              <div v-else>
                {{ record.thirdMdNum }}
              </div>
            </template>
            <template slot="remarks" slot-scope="text, record">
              <div v-if="record.isEdit">
                <BaseInput placeholder="请输入" v-model="record.remarks" />
              </div>
              <div v-else>
                <a-tooltip>
                  <template #title>{{ record.remarks }}</template>
                  {{ record.remarks }}
                </a-tooltip>
              </div>
            </template>
            <template slot="planInTime" slot-scope="text, record">
              <div v-if="record.isEdit">
                <a-date-picker placeholder="请选择" value-format="YYYY-MM-DD"
                               v-model="record.planInTime" />
              </div>
              <div v-else>{{ record.planInTime }}</div>
            </template>
            <template slot="stopUseTime" slot-scope="text, record">
              <div v-if="record.isEdit">
                <a-date-picker placeholder="请选择" value-format="YYYY-MM-DD"
                               v-model="record.stopUseTime" />
              </div>
              <div v-else>{{ record.stopUseTime }}</div>
            </template>
            <template slot="actions" slot-scope="text, record">
              <div class="operStyle">
                <a-button type="link" @click="handleEdit(record)"
                          v-if="queryParams.editModel == 3 && record.couldUpdate">
                  编辑
                </a-button>
                <a-button type="link" @click="handleDelete(record)" v-if="record.couldUpdate && queryParams.editModel*1!=0">
                  删除
                </a-button>
              </div>
            </template>
          </b-table>
        </a-card>
      </a-spin>
    </a-form-model>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <div v-if="queryParams.editModel != 0 && !isAudit">
        <a-button :loading="loading[0]" :disabled="loading[1]" type="primary" class="button_right"
                  @click="handleSubmit(0)">保存草稿</a-button>
        <a-button :loading="loading[1]" :disabled="loading[0]" type="primary" class="button_right"
                  @click="handleSubmit(1)">提交</a-button>
      </div>
      <a-button  @click="handleActiveClose">关闭</a-button>
    </div>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import api from '@/api/quality/equipmentConfigurationPlan' // api
import equipmentNameApi from '@/api/quality/equipmentNameManagement' // 计量设备名称管理api
export default {
  name: "equipmentConfigurationPlanInfo",
  extends: new BaseEditPage(),
  data() {
    const columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'number',
        customRender() {
          return arguments[2] + 1
        }
      },
      {
        title: '设备名称',
        dataIndex: 'mdId',
        width: 200,
        scopedSlots: { customRender: 'mdId' }
      },
      {
        title: '规格型号',
        dataIndex: 'mdModelId',
        width: 200,
        scopedSlots: { customRender: 'mdModelId' }
      },
      {
        title: '计划设备数量（个）',
        dataIndex: 'planMdCount',
        children: [
          {
            title: '总数',
            dataIndex: 'planMdTotal',
            width: 150,
            scopedSlots: { customRender: 'planMdTotal' }
          },
          {
            title: '自有设备数量',
            dataIndex: 'ownMdNum',
            width: 150,
            scopedSlots: { customRender: 'ownMdNum' }
          },
          {
            title: '分包设备数量',
            dataIndex: 'thirdMdNum',
            width: 150,
            scopedSlots: { customRender: 'thirdMdNum' }
          },
        ]
      },
      {
        title: '落实设备数量（个）',
        dataIndex: 'executeMdCount',
        children: [
          {
            title: '总数',
            dataIndex: 'executeMdTotal',
            width: 150,
          },
          {
            title: '自有设备数量',
            dataIndex: 'executeOwnMdNum',
            width: 150,
          },
          {
            title: '分包设备数量',
            dataIndex: 'executeThirdMdNum',
            width: 150,
          },
        ]
      },
      {
        title: '计划进场时间',
        dataIndex: 'planInTime',
        width: 180,
        scopedSlots: { customRender: 'planInTime' }
      },
      {
        title: '实际进场时间',
        dataIndex: 'actualInTime',
        width: 180,
      },
      {
        title: '使用截止期限',
        dataIndex: 'stopUseTime',
        width: 180,
        scopedSlots: { customRender: 'stopUseTime' }
      },
      {
        title: '备注',
        dataIndex: 'remarks',
        width: 220,
        scopedSlots: { customRender: 'remarks' }
      },
      {
        title: '操作',
        dataIndex: 'actions',
        width: 180,
        fixed: 'right',
        align: 'center',
        scopedSlots: { customRender: 'actions' }
      }
    ]
    let [showFieldArr, columnsData, fixedDataColumn] = [[], [], ['number', 'mdId', 'mdModelId', 'planMdCount']]
    if (this.$route.query.editModel != 0) {
      showFieldArr = [...fixedDataColumn, ...['planInTime', 'stopUseTime', 'remarks', 'actions']]
    } else {
      showFieldArr = [...fixedDataColumn, ...['executeMdCount', 'planInTime', 'actualInTime', 'stopUseTime', 'remarks']]
    }
    this.$clone(columns).forEach((item) => {
      if (showFieldArr.includes(item.dataIndex)) {
        columnsData.push(item);
      }
    });
    return {
      spinning: false,
      loading: { 0: false, 1: false }, //页面及按钮loading
      queryParams: this.$route.query,//页面路由参数
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),//当前用户信息
      api,
      equipmentNameApi, //api,
      deviceNameData: [],//设备名称list
      form: {
        planList: [],
      },
      formList: [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          disabled: true,
        },
        {
          label: '填报人',
          keyName: 'fillInUserName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '填报时间',
          keyName: 'fillInTime',
          slot: true,
        },
      ],
      columns: columnsData,
      rules: {},
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.queryParams.editModel = 0;
          })
        }
      },
    },
  },
  async mounted() {
    //获取设备名称下拉数据源
    this.getDeviceNameList();
    //获取详情
    this.getDetailInfo();
    //获取流程配置值
    this.processConfig = await this.$getConfigFn('metering_device_config_project_audit');
  },
  methods: {
    /**
     * @description: 获取可用的设备列表
     */
    async getDeviceNameList() {
      let pageParams = {
        pageNum: 1,
        pageSize: 0
      };
      const requestParameters = Object.assign({}, pageParams, { param: { status: 0 } })
      let res = await this.equipmentNameApi.list(requestParameters);
      if (res.code === '0') {
        this.deviceNameData = res.data.list || []
      }
    },
    /**
     * @description: 获取规格型号
     * @param {String} mdId 设备名称ID
     */
    getMdModelData(mdId) {
      if (this.deviceNameData.length && mdId) {
        let _obj = this.deviceNameData.find((item) => item.id == mdId);
        return _obj && Object.keys(_obj).length ? _obj.list : [];
      } else {
        return [];
      }
    },
    /**
      * @description: 获取详情
      */
    getDetailInfo() {
      const _editModel = this.queryParams.editModel;
      let params = {
        id: this.queryParams.id,
        versionId: this.queryParams.approvalStatus == '-1' ? "" : this.queryParams.versionId 
      }
      !params.versionId && delete params.versionId;
      this.loading[0] = true
      this.spinning = true;
      this.api.getDetail(params).then((res) => {
        this.loading[0] = false;
        this.spinning = false;
        if (res.code === '0') {
          let _data = res.data;
          if (_editModel == 0) {
            this.form.fillInUserId = _data.fillInUserId;
            this.form.fillInUserName = _data.fillInUserName;
            this.form.fillInTime = _data.fillInTime;
          } else {
            this.form.fillInUserId = this.userInfo.id;
            this.form.fillInUserName = this.userInfo.name;
            this.form.fillInTime = this.$dateFormat(new Date(), 'D')
          }
          this.form.projectId = _data.projectId;
          this.form.configProjectId = _data.id;
          if (_editModel != 1) {
            this.form.planList = _data.planList || [];
            if (this.form.planList && this.form.planList.length) {
              this.form.planList.forEach((item, index) => {
                this.$set(item, 'key', `row${index + 1}`);
                this.$set(item, 'isEdit', _editModel == 2 ? true : false)
              })
            }
          } else {
            this.form.planList = [];
          }
        }
      }).catch((err) => {
        this.loading[0] = false;
        this.spinning = false;
      })
    },
    /**
     * @description: 新增行
     */
    handleAdd() {
      const obj = {
        key: `row${this.form.planList.length + 1}`,
        isEdit: true,
        couldUpdate: true,
      };
      this.form.planList.push(obj)
    },
    /**
    * @description: 操作删除
    * @param {Object} record 当前行数据
    */
    handleDelete(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定删除当前配置计划项？',
        onOk: () => {
          this.form.planList = this.form.planList.filter((i) => i.key !== record.key)
        }
      })
    },
    /**
    * @description: 操作编辑
    * @param {Object} record 当前行数据
    */
    handleEdit(record) {
      this.$set(record, "isEdit", true);
    },
    /**
    * @description: 提交表单
    * @param {Number} statusCode 0:保存草稿 1:提交
    */
    handleSubmit(statusCode) {
      let that = this;
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          // 校验计划项表单
          if (that.form.planList.length > 0) {
            for (let index in that.form.planList) {
              let item = that.form.planList[index] // 行数据源
              let keys = {
                mdId: '设备名称',
                mdModelId: "格型号",
                planMdTotal: '计划设备总数',
                ownMdNum: '计划自有设备数量',
                planInTime: '计划进场时间',
                stopUseTime: '使用截止期限'
              } // 需要校验的对象
              for (let i in keys) {
                // 存在于校验对象，且表单值为空或不存在时提示
                if (!Object.keys(item).includes(i) || (Object.keys(item).includes(i) && !item[i])) {
                  that.$message.warning(`序号${Number(index) + 1}的${keys[i]}不能为空！`)
                  return
                }
              }
            }
          } else {
            that.$message.warning('配置计划项不能为空')
            return
          }
          statusCode === 0 && that.$refs.ruleForm.clearValidate();
          let params = Object.assign({}, that.form)
          params.planList.forEach((item) => {
            if (item.planInTime) item.planInTime = item.planInTime + ' 00:00:00'
            if (item.stopUseTime) item.stopUseTime = item.stopUseTime + ' 00:00:00'
            if (item.actualInTime) item.actualInTime = item.actualInTime + ' 00:00:00'
          })
          that.loading[statusCode] = true
          //提交时需要走审批流程
          if (statusCode == 1) {
            that.submitApprovalConfirm(that.processConfig, (flag) => {
              if (!flag) {
                that.loading[statusCode] = false
                return
              }
              that.sendRequest(statusCode, params);
            })
          } else {
            that.sendRequest(statusCode, params);
          }
        } else {
          that.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     * @description: 发送请求
     * @param {Number} statusCode 0:保存草稿 1:提交
     * @param {Object} params 请求参数
     */
    sendRequest(statusCode, params) {
      let name = ['saveDraft', 'commit'][statusCode] // 根据操作切换url地址
      this.setProcessConfig = null;
      this.api[name](params).then((res) => {
        if (res.code === '0') {
          this.loading[statusCode] = false
          this.$message.success(['保存', '提交'][statusCode] + '成功！')
          if (statusCode == 1) {
            //提交时，返回id
            this.businessId = this.queryParams.id;
            this.setProcessConfig = this.processConfig;
            return;
          } else {
            this.$multiTab.close()
          }
        }
      }).catch((err) => {
        this.loading[statusCode] = false
      })
    },
    /**
     * @description: 选中设备名称
     * @param {Object} record 当前行数据
     */
    handleSelect(record) {
      this.$set(record, "mdModelId", undefined)
    },
    /**
     * @description: 计划设备总数验证
     * @param {String} e 值
     * @param {String} index 行index
     */
    planMdTotaBlur(e, index) {
      if (this.form.planList[index].ownMdNum) {
        if (e < this.form.planList[index].ownMdNum) {
          this.$message.warning('计划设备总数需大于或等于计划自有设备数量')
          this.form.planList[index].planMdTotal = null;
          this.form.planList[index].thirdMdNum = null;
        } else {
          this.subEquipmentCount(index);
        }
      }
    },
    /**
     * @description: 计划自有设备数量验证
     * @param {String} e 值
     * @param {String} index 行index
     */
    ownMdNumBlur(e, index) {
      if (this.form.planList[index].planMdTotal) {
        if (e > this.form.planList[index].planMdTotal) {
          this.$message.warning('计划自有设备数量需小于或等于计划设备总数')
          this.form.planList[index].ownMdNum = null;
          this.form.planList[index].thirdMdNum = null;
        } else {
          this.subEquipmentCount(index);
        }
      }
    },
    /**
     * @description: 分包设备数量计算
     * @param {String} index 行index
     */
    subEquipmentCount(index) {
      this.$set(this.form.planList[index], "thirdMdNum", this.form.planList[index].planMdTotal - this.form.planList[index].ownMdNum)
    }
  },
}
</script>

<style>
.operStyle {
  height: 38px;
}
</style>